<script setup lang="ts">
import { onMounted, ref, provide } from 'vue';
import { useRouter } from 'vue-router';
import { ThemeServiceInit, devuiLightTheme, devuiDarkTheme } from 'devui-theme';

const router = useRouter();

// 声明全局类型
declare global {
  interface Window {
    vscode?: {
      postMessage: (message: any) => void
    }
  }
}

// Theme Management
const themeService = ThemeServiceInit(
  {
    'ide-light': devuiLightTheme,
    'ide-dark': devuiDarkTheme,
  },
  'ide-dark'
);
const themeChange = (isDark: boolean) => {
  if (themeService) {
    themeService.applyTheme(isDark ? devuiDarkTheme : devuiLightTheme);
  }
};

// Login State Management
const isCheckingAuth = ref(true);
const isLoggedIn = ref(false);
const userInfo = ref(null);
const loginMessage = ref('请使用第三方登录以开始使用 HarmonyPilot');
const apiKey = ref('');
const logo2Png = ref(`${window.staticPath}/resource/logo/Hi.svg`);

// Provide API key to child components
provide('apiKey', apiKey);

// Login Functions
const handleThirdPartyLogin = () => {
    window?.vscode.postMessage({
        messageType: 'openThirdPartyLogin'
    });
};

const checkAuthStatus = () => {
    isCheckingAuth.value = true;
    window?.vscode.postMessage({
        messageType: 'checkAuthStatus'
    });
};

// Lifecycle and Message Handling
onMounted(() => {
  window.addEventListener('message', (event) => {
    const message = event.data;
    // Navigation
    if (message.messageType === 'navigateTo') {
      router.push(message.data.page);
    } 
    // Theme
    else if (message.messageType === 'themeChange') {
      themeChange(message.data.isDark);
    }
    // Auth
    else if (message.messageType === 'authStatusResult') {
        if (message.data.isLoggedIn) {
            isLoggedIn.value = true;
        } else {
            isLoggedIn.value = false;
        }
        isCheckingAuth.value = false;
    } else if (message.messageType === 'loginRequired') {
        isLoggedIn.value = false;
        isCheckingAuth.value = false;
        loginMessage.value = message.data.message || '请使用第三方登录重新登录';
    } else if (message.messageType === 'thirdPartyLoginSuccess') {
        isLoggedIn.value = true;
        apiKey.value = message.data.apiKey || '';
        loginMessage.value = '登录成功！';
    } else if (message.messageType === 'thirdPartyLoginFailed') {
        isLoggedIn.value = false;
        loginMessage.value = message.data.message || '登录失败，请重试';
    } else if (message.messageType === 'loginStatusChanged') {
        isLoggedIn.value = message.data.isLoggedIn;
        userInfo.value = message.data.userInfo;
        isCheckingAuth.value = false;
        if (message.data.isLoggedIn) {
            loginMessage.value = `欢迎, ${message.data.userInfo.cnName}!`;
        } else {
            loginMessage.value = '您已登出，请重新登录。';
        }
    }
  });

  // Initial requests
  window.vscode.postMessage({ messageType: 'getTheme' });
  checkAuthStatus();
});
</script>

<template>
  <div class="app">
    <div v-if="isCheckingAuth" class="auth-checking-container">
      <div class="auth-checking-box">
        <McIntroduction :logo-img="logo2Png" title="HarmonyPilot" sub-title="正在验证登录状态..." class="headerIcon2x" />
        <div class="loading-indicator">
          <i class="icon-loading"></i>
          <span>请稍候...</span>
        </div>
      </div>
    </div>
    <div v-else-if="!isLoggedIn" class="login-container">
      <div class="login-box">
        <McIntroduction :logo-img="logo2Png" title="HarmonyPilot" sub-title="欢迎使用 HarmonyPilot" class="headerIcon2x" />
        <div class="login-prompt">
          <p>{{ loginMessage }}</p>
          <div class="login-actions">
            <d-button @click="handleThirdPartyLogin" variant="solid" color="primary">
              第三方登录
            </d-button>
          </div>
        </div>
      </div>
    </div>
    <router-view v-else />
  </div>
</template>

<style scoped>
.app {
  height: 100vh;
}

:deep(.headerIcon2x) {
  img {
    height: 64px;
    width: 64px;
  }
}

.auth-checking-container,
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  flex-direction: column;
  text-align: center;
  background-color: var(--devui-global-bg);
}

.auth-checking-box,
.login-box {
  padding: 3rem;
  border-radius: 12px;
  width: 100%;
  max-width: 450px;
  background-color: var(--devui-area);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-top: 2rem;
  color: var(--devui-text);
  font-size: var(--devui-font-size);
}

.loading-indicator i {
  font-size: 1.2rem;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.login-prompt {
  margin: 2rem 0;
}

.login-prompt p {
  color: var(--devui-text);
  font-size: var(--devui-font-size);
  margin-bottom: 1.5rem;
  line-height: 1.5;
}

.login-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  flex-wrap: wrap;
}
</style>
